import _ from 'lodash'
import { Locale, Locales } from '@/messages/locale'
import { ResourceBundle, bundles } from '@/messages/resource-bundle'
import { MessageFormat, ReplaceMessageFormat } from '@/messages/message-format'

export interface MessageSource {
  getMessage (
    code: string,
    args: string[],
    locale: Locale,
    defaultMessage?: string
  ): string
}

export default class SimpleMessageSource implements MessageSource {
  defaultLocale: Locale = Locales.forName('zh')

  constructor (defaultLocale?: Locale) {
    if (defaultLocale) {
      this.defaultLocale = defaultLocale
    }
  }

  getMessageInternal (code: string, args: string[], locale?: Locale): string {
    if (!code) {
      return null
    }
    const localeToUser = locale || this.defaultLocale
    const format = this.resolveCode(code, localeToUser)
    return format.parse(args, localeToUser)
  }

  resolveCode (code: string, locale: Locale): MessageFormat {
    const bundle = this.getResourceBundle(locale)
    return this.getMessageFormat(code, bundle)
  }

  getResourceBundle (locale: Locale): ResourceBundle {
    return bundles.getBundle(locale)
  }

  getMessageFormat (code: string, bundle: ResourceBundle): MessageFormat {
    const pattern = bundle.getString(code)
    return new ReplaceMessageFormat(pattern)
  }

  getMessage (
    code: string,
    args: string[],
    locale: Locale,
    defaultMessage?: string
  ): string {
    const msg = this.getMessageInternal(code, args, locale)
    if (msg) {
      return msg
    }
    if (defaultMessage) {
      return defaultMessage
    }
    return code
  }
}
